<template>
  <div class="login-container">
    <div class="login-form">
      <h2>影像学辅助诊断系统</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="用户名或患者ID（数字）"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="userStore.isLoading" class="login-btn">
            登录
          </el-button>
        </el-form-item>
      </el-form>
      <div v-if="userStore.error" class="error-message">
        {{ userStore.error }}
      </div>
      <div class="login-tips">
        <p>医生账号: doctor1 / 123456</p>
        <p>患者账号: 直接输入“患者ID数字”登录（密码任意）</p>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/user';

export default {
  name: 'Login',
  setup() {
    const router = useRouter();
    const userStore = useUserStore();
    const loginFormRef = ref(null);
    
    const loginForm = ref({
      username: '',
      password: ''
    });
    
    const rules = {
      username: [
        { required: true, message: '请输入用户名或患者ID', trigger: 'blur' }
      ],
      password: [
        { required: false, message: '请输入密码', trigger: 'blur' }
      ]
    };
    
    const handleLogin = async () => {
      if (!loginFormRef.value) return;
      
      loginFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const user = await userStore.login(loginForm.value.username, loginForm.value.password);
            // 根据用户角色跳转到不同页面
            if (user.role === 'doctor') {
              router.push('/doctor-home');
            } else if (user.role === 'patient') {
              router.push('/patient-home');
            }
          } catch (error) {
            // 错误已经在store中处理
          }
        }
      });
    };
    
    return {
      loginForm,
      rules,
      loginFormRef,
      userStore,
      handleLogin
    };
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-form {
  background: white;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 400px;
}

.login-form h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
}

.login-btn {
  width: 100%;
}

.error-message {
  color: #f56c6c;
  text-align: center;
  margin-top: 15px;
}

.login-tips {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  font-size: 12px;
  color: #909399;
}

.login-tips p {
  margin: 5px 0;
}
</style>